﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace P2P_Backup.connections
{
    public class LocalPeerConnection
    {
        TcpListener tcpListener;
        IPEndPoint endPoint;

        public LocalPeerConnection(IPEndPoint endPoint)
        {
            this.endPoint = endPoint;
            tcpListener = new TcpListener(endPoint);
             tcpListener.Start();

            startTcpListener();
            Console.WriteLine("Started Listening for Peer connections");
        }

        private void startTcpListener()
        {
            tcpListener.BeginAcceptTcpClient(new AsyncCallback(ReceiveTcp), endPoint);
        }
        private void ReceiveTcp(IAsyncResult ar)
        {
            TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
            IPEndPoint endPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;

            Console.WriteLine(String.Format("Connection recieved from: {0}", endPoint));
            RemotePeer peer = new RemotePeer(endPoint.Address, default(string), tcpClient);                        

            startTcpListener();
        }
    }
}
